module.exports = (options) => {
    return async (ctx, next) => {
        const LogApiList = ctx.app.config.LogApiList
        const apiUrl = ctx.request.url.split('?')[0]

        let webServerLog, token, visitor = '游客'

        // 需要记录日志
        if (LogApiList.indexOf(apiUrl) != -1) {
            webServerLog = ctx.getLogger('webServer')
            //拿到token
            token = ctx.request.header.authorization
            if (token) {
                const {secret} = ctx.app.config.jwt
                const {userId} = ctx.app.jwt.verify(token, secret);
                visitor = `用户 ${userId}`
            }
            if (ctx.request.method == 'GET') {
                webServerLog.info(`${visitor} req query: %j`, ctx.request.query)
            } else {
                webServerLog.info(`${visitor} req data: %j`, ctx.request.body);
            }
        }
        

        try {
            const result = await next();
            if (LogApiList.indexOf(apiUrl) != -1) webServerLog.info(`${visitor} res result: %j`, result)

            ctx.body = {
                code: '00',
                data: result
            }
        } catch (err) {
            console.log(err);
            if (LogApiList.indexOf(apiUrl) != -1) webServerLog.error(`${visitor} error result: %j`, err)

            ctx.body = {
                code: err.code || '03',
                msg: err.msg || err
            }
        }
    }
}